package com.zk.zklockfororderno;


import org.I0Itec.zkclient.IZkDataListener;

import java.util.concurrent.CountDownLatch;

public class LockABImpl extends LockAB {

    CountDownLatch latch = null;

    @Override
    protected void waitlock() {
        IZkDataListener iZkDataListener = new IZkDataListener() {

            @Override
            public void handleDataChange(String s, Object o) throws Exception {
                if (latch!=null){
                    latch.countDown();
                }
            }

            @Override
            public void handleDataDeleted(String s) throws Exception {
            }
        };

        //注册到zkClient进行监听 #@#$######################################
        zkClient.subscribeDataChanges(ZKLOCK,iZkDataListener);
        //注册到zkClient进行监听 #@#$######################################

        if (zkClient.exists(ZKLOCK)){
            latch = new CountDownLatch(1);
            try {
                latch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }



    @Override
    protected boolean trylock() {
        try {
            zkClient.createEphemeral(ZKLOCK);
            return true;
        } catch (Exception e) {
//            e.printStackTrace();
            return false;
        }
    }
}
